<?php

/**
 * uniBoard Templates find & replace
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date $
 * $Revision: 64 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_tpl_find{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore	= NULL;
	
	/**
	 * Avaiable styles
	 *
	 * @var array
	 */
	
	private $styles		= array();
		
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;
	
		// Make styles list
		$this -> styles = $appCore -> getStyles( DEVELOPER_MODE);
		
		// Search?
		if ( $appCore -> _POST( 'search') == 1)
		{
			// Do search
			$this -> doSearch();
			
		}
		else
		{
			// Draw Form
			$this -> drawForm();
		}
			
	}

	// ------------------------------------------------------------------------

	/**
	 * Does search
	 *
	 */
	
	function doSearch(){
		
		// Grab styles to search
		$styles = $this -> appCore -> listInput( 'select_styles');
		
		// Sort out nonexistant styles
		foreach ( $styles as $key => $style_id)
		{
			if ( !isset( $this -> styles[$style_id]))
			{
				unset( $styles[$key]);
			}
		}
		
		// Grab search phrase
		$search = $this -> appCore -> _POST( 'tpl_search');
		
		// Try-catch
		try
		{
			// No styles selected?
			if ( empty( $styles))
			{
				throw new exc_small( $this -> appCore -> lang['acp_template_search_no_styles']);
			}
			
			// Empty search phrase?
			if ( !isset( $search[0]))
			{
				throw new exc_small( $this -> appCore -> lang['acp_template_search_find_empty']);
			}
			
			// Grab replace phrase
			$replace = $this -> appCore -> _POST( 'tpl_replace');
			
			// Select templates
			if (isset($replace[0]))
			{
				// lowercase search
				$search_l = strtolower( $search);
				
				// Select template_code column too
				$this -> appCore -> db -> query( 'SELECT t.template_id, t.template_group, t.template_name, t.template_code, s.style_id, s.style_name
				FROM ' . DB_PREFIX . 'styles_templates t
				LEFT JOIN ' . DB_PREFIX . 'styles s ON t.style_id = s.style_id
				WHERE t.template_code LIKE \'%' . $this -> appCore -> db -> strEscape( $search, true) . '%\'');
			}
			else
			{
				$this -> appCore -> db -> query( 'SELECT t.template_id, t.template_group, t.template_name, s.style_id, s.style_name
				FROM ' . DB_PREFIX . 'styles_templates t
				LEFT JOIN ' . DB_PREFIX . 'styles s ON t.style_id = s.style_id
				WHERE t.template_code LIKE \'%' . $this -> appCore -> db -> strEscape( $search, true) . '%\'');
			}
			
			// Anything found?
			if ( $this -> appCore -> db -> numRows() > 0)
			{
				// Start output buffer
				ob_start();
		
				// Open table with results
				echo $this -> appCore -> output -> openTableBlock( $this -> appCore -> lang['tpl_find_replace_form_results'] . ': ' . $this -> appCore -> number( $this -> appCore -> db -> numRows()));
				
				// Draw header
				echo $this -> appCore -> output -> tableHeader( array(
					array(
						'left_float width_long',
						$this -> appCore -> lang['tpl_find_form_result_tpl']
					),
					array(
						'right_float width_quarter',
						$this -> appCore -> lang['tpl_find_form_result_style']
					),
					array(
						'right_float width_quarter',
						$this -> appCore -> lang['tpl_find_form_result_group']
					)
				));
				
				// Draw results
				while ( $tpl_result = $this -> appCore -> db -> fetch_assoc())
				{
					// Draw row
					echo $this -> appCore -> output -> tableRow('
						<div class="cell left_float width_long">
							<a href="' . $this -> appCore -> adminLink( 'act=edit_template&do=edit&tpl=' . $tpl_result['template_id']) . '" class="item_title">' . htmlspecialchars( $tpl_result['template_name']) . '</a>' . ( isset($replace[0]) ? ' <span class="item_append">(' . substr_count( strtolower( $tpl_result['template_code']), $search_l) . $this -> appCore -> lang['tpl_find_form_result_instances'] . ')</span>' : '') . '
						</div>
						<div class="cell left_border right_float width_quarter center">
							<a href="' . $this -> appCore -> adminLink( 'act=templates&style=' . $tpl_result['style_id']) . '">' . htmlspecialchars( $tpl_result['style_name']) . '</a>
						</div>
						<div class="cell left_border right_float width_quarter center">
							<a href="' . $this -> appCore -> adminLink( 'act=templates&style=' . $tpl_result['style_id'] . '&show=' . urlencode( $tpl_result['template_group'])) . '">' . htmlspecialchars( isset( $this -> appCore -> lang['tpl_group_' . $tpl_result['template_group']]) ? $this -> appCore -> lang['tpl_group_' . $tpl_result['template_group']] : $tpl_result['template_group']) . '</a>
						</div>');
					
					// Replace in template
					if (isset( $replace[0]))
					{
						$this -> appCore -> db -> update( array( 'template_code' => $this -> appCore -> db -> strEscape( str_ireplace( $search, $replace, $tpl_result['template_code']))), 'styles_templates', 'template_id = \'' . $tpl_result['template_id'] . '\'');
					}
				}
				
				// Close table with results
				echo $this -> appCore -> output -> closeTableBlock();
				
				// Any replaces?
				if ( isset( $replace[0]))
				{	
					// Create Log
					$this -> appCore -> logAdmin( 'log_admin_imported_style', htmlspecialchars( $this -> api -> style_name));
				}
				
				// Free result
				$this -> appCore -> db -> freeResult();
				
				// Draw output
				$this -> appCore -> output -> draw( $this -> appCore -> lang['acp_template_search'], array(
					$this -> appCore -> adminLink( 'act=tpl_find') => $this -> appCore -> lang['acp_template_search'],
					'' => $this -> appCore -> lang['tpl_find_replace_form_results']
				), ob_get_clean());
			}
			else
			{
				// Free result
				$this -> appCore -> db -> freeResult();
				
				// Nothing found
				throw new exc_small( $this -> appCore -> lang['acp_template_search_nothing_found']);
			}
		}
		catch ( exc_small $error)
		{
			// Draw Error
			$this -> appCore -> output -> error( $error -> getMessage(), $this -> appCore -> lang['tpl_find_form_find']);
			
			// Repeat form
			$this -> drawForm();
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Displays "Find and Replace" form
	 *
	 */
	
	function drawForm(){
		
		// Load fields templates
		$this -> appCore -> templates['form_inputs'] = new tpl_form_inputs( $this -> appCore);
		
		// Start output buffer
		ob_start();
		
		// New style form start
		echo $this -> appCore -> output -> openForm( $this -> appCore -> adminLink( 'act=tpl_find'));
		echo $this -> appCore -> drawHidden( 'search', 1);
		echo $this -> appCore -> output -> openFormBlock( $this -> appCore -> lang['tpl_find_replace_form']);
		
		// Draw fields
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['tpl_find_form_styles'], $this -> appCore -> drawMultiList( 'select_styles', $this -> styles, $this -> appCore -> listInput( 'select_styles')), $this -> appCore -> lang['tpl_find_form_styles_expl']);
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['tpl_find_form_find'], $this -> appCore -> drawTextArea( 'tpl_search', $this -> appCore -> _POST( 'tpl_search')));
		echo $this -> appCore -> output -> formItem( $this -> appCore -> lang['tpl_find_form_replace'], $this -> appCore -> drawTextArea( 'tpl_replace', $this -> appCore -> _POST( 'tpl_replace')), $this -> appCore -> lang['tpl_find_form_replace_expl']);
		
		// New style form close
		echo $this -> appCore -> output -> submitButton( $this -> appCore -> lang['run_tool']);
		echo $this -> appCore -> output -> closeFormBlock();
		echo $this -> appCore -> output -> closeForm();
		
		// Draw output
		$this -> appCore -> output -> draw( $this -> appCore -> lang['acp_template_search'], array(
			$this -> appCore -> adminLink( 'act=tpl_find') => $this -> appCore -> lang['acp_template_search'],
		), ob_get_clean());
		
	}
	
}